package com.qtummatrix.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qtummatrix.entity.Equipment;
import com.qtummatrix.service.EquipmentService;
import com.qtummatrix.service.LaboratoryService;
import com.qtummatrix.utils.ExcelUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 设备管理Controller
 * create by Gongshiyong  2020-01-22 15:08
 */
@Controller
@RequestMapping("tecParamManagement")
public class tecParamManagementController {

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private LaboratoryService laboratoryService;

    private Map<String, Object> map = new HashMap<>();

    /**
     * 从主页跳转到设备管理页面
     *
     * @return
     */
    @RequestMapping("toTecParamManagement")
    public ModelAndView toTecParamManagement() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("tecparaManagement");
        return modelAndView;
    }

    /**
     * 查询所有的设备技术参数
     *
     * @param equipment 设备对象
     * @param pageNo    当前页码
     * @param pageSize  一页显示多少条数据
     * @return
     */
    @ResponseBody
    @GetMapping("selectAllEquipmentInfo")
    public PageInfo selectAllEquipmentInfo(Equipment equipment, Integer pageNo, Integer pageSize) {
        return equipmentService.selectAllEquipmentInfo(equipment, pageNo, pageSize);
    }

    /**
     * 获取下拉框中的实验室信息
     *
     * @return
     */
    @ResponseBody
    @GetMapping("getAllLabInfo")
    public Object getAllLabInfo() {
        return laboratoryService.selectAllLabInfoNoPage();
    }

    /**
     * 根据主键id查询设备信息
     *
     * @param id 设备id
     * @return
     */
    @ResponseBody
    @GetMapping("selectByPrimaryKey")
    public Object selectByPrimaryKey(Integer id) {
        return equipmentService.selectByPrimaryKey(id);
    }

    /**
     * 保存修改后的信息或者新建设备信息
     *
     * @param equipment 设备对象
     * @return
     */
    @ResponseBody
    @PutMapping("updateByPrimaryKeySelective")
    public Map<String, Object> updateByPrimaryKeySelective(Equipment equipment) {
        int i = 0;
        if (equipment.getId() != null) {
            i = equipmentService.updateByPrimaryKeySelective(equipment);
        } else {
            i = equipmentService.insertSelective(equipment);
        }
        if (i > 0) {
            map.put("resultCode", "200");
            map.put("resultMessage", "保存成功！");
        } else {
            map.put("resultCode", "201");
            map.put("resultMessage", "保存失败！");
        }
        return map;
    }

    /**
     * 删除设备
     *
     * @param id 设备id
     * @return
     */
    @ResponseBody
    @DeleteMapping("deleteByPrimaryKey")
    public Map<String, Object> deleteByPrimaryKey(Integer id) {
        int i = equipmentService.deleteByPrimaryKey(id);
        if (i > 0) {
            map.put("resultCode", "200");
            map.put("resultMessage", "删除成功！");
        } else {
            map.put("resultCode", "201");
            map.put("resultMessage", "删除失败！");
        }
        return map;
    }

    /**
     * 导出数据为excel
     *
     * @param ids      要导出的数据的id字符串
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public void exportExcel(String ids, HttpServletResponse response) {
        try {
            Collection collection = equipmentService.selectEquipmentInfoExcel(ids);
            //调用工具类进行文件的导出
            ExcelUtil.getExcel(response, collection, "equipment.xlsx");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出模板文件
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @GetMapping("exportVehicleInfo")
    public void downLoadTemplate(HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //从服务器读取文件
            String realPath = request.getServletContext().getRealPath("");
            File file = new File(realPath + "/file/" + "设备新增模板.xls");
            response.setContentLength((int) file.length());
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            inputStream = new FileInputStream(file);
            //写入本地
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 批量导入设备
     *
     * @param uploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping("UploadExcel")
    public Object UploadExcel(MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        System.out.println(uploadFile.getOriginalFilename());

        if (uploadFile.isEmpty()) {
            request.getServletContext().getRealPath("");
            String filePath = "/file/设备新增模板.xls";
        //TODO
        }
        return this.map;
    }


    /**
     * 批量删除数据
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @DeleteMapping("batchDeleteData")
    public Object batchDeleteData(String ids) {
        int i = equipmentService.batchDeleteData(ids);
        if (i == 1) {
            map.put("resultMessage", "删除成功");
        } else {
            map.put("resultMessage", "删除失败");
        }
        return map;
    }

    /**
     * 上传图片到nginx服务器
     *
     * @param ImgPath 图片对象
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("upload")
    public Object uploadImg(MultipartFile ImgPath) throws IOException {
        if (!ImgPath.isEmpty()) {
            //获取服务器上传路径
            String path = "D:\\softInstall\\nginx-1.12.2\\html\\images";
            //获取文件名称
            String filename = ImgPath.getOriginalFilename();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
            String prefix = df.format(new Date());
            filename = prefix + filename.substring(filename.indexOf('.'));
            File file = new File(path, filename);
            if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".bmp") || filename.endsWith(".jpeg")) {
                //不完成文件上传，在提交时上传图片到图片服务器
                ImgPath.transferTo(file);
                map.put("uploadMsg", "图片上传成功");
                map.put("imgPath", filename);
                map.put("resultCode", "200");
            } else {
                map.put("uploadMsg", "请选择[.jpg]、[.png]、[.bmp]、[.jpeg]、[.gif]格式的图片进行上传！");
                map.put("resultCode", "201");
            }
        }
        return map;
    }

    /**
     * 保存图片到数据库中
     *
     * @param id        设备id
     * @param imagePath 图片路径
     * @return
     */
    @ResponseBody
    @PutMapping("uploadImage")
    public Map uploadImage(Integer id, String imagePath) {
        int i = equipmentService.uploadImage(id, imagePath);
        if (i > 0) {
            map.put("resultCode", "200");
        } else {
            map.put("resultCode", "201");
        }
        return map;
    }

}
